Kameleon-Plus  0.3.2
Utils.h
Go to the documentation of this file.
1 /*
2  * Utils.h
3  *
4  * Created on: Jul 10, 2009
5  * Author: dberrios
6  */
7 
8 #ifndef UTILS_H_
9 #define UTILS_H_
10 
11 namespace ccmc
12 {
13  template<class T>
14  class Utils
15  {
16  public:
17  Utils();
18  static int binary_search(const std::vector<T>& vec, unsigned int start, unsigned int end, const T& key);
19  virtual ~Utils();
20  };
21 
30  template<class T>
31  int Utils<T>::binary_search(const std::vector<T>& vec, unsigned int start, unsigned int end, const T& key)
32  {
33  // Termination condition: start index greater than end index
34 
35  if (start > end)
36  {
37  return -1;
38  }
39 
40  // Find the middle element of the vector and use that for splitting
41  // the array into two pieces.
42  unsigned int middle = (start + ((end - start) / 2));
43 
44  //outside valid range
45  if (middle > vec.size())
46  return -1;
47 
48  if (key == vec[middle])
49  {
50  return middle;
51  } else if (key < vec[middle + 1] && key >= vec[middle])
52  {
53  return middle;
54  } else if (key < vec[middle])
55  {
56  return binary_search(vec, start, middle - 1, key);
57  }
58  return binary_search(vec, middle + 1, end, key);
59  }
60 }
61 #endif /* UTILS_H_ */